/******************** (C) COPYRIGHT 2018 merafour ********************
* Author             : 冷月追风@merafour.blog.163.com
* Version            : V1.0.0
* Date               : 12/1/2019
* Description        : 数据格式转换,需根据数据的存储格式相应调整代码.
********************************************************************************
* merafour.blog.163.com
* merafour@163.com
* github.com/Merafour
*******************************************************************************/
#ifndef CJSONFORMAT_H
#define CJSONFORMAT_H
#include <QDebug>
#include <stdint.h>
#include "cJSON.h"

class cJSONformat
{
public:
    cJSONformat();
    int format_cutover(const char* open_path, const char* save_path);

private:
    cJSON* format_decode(const char* imagebyte);
    char* open(const char *path)
    {
        size_t _size=0;
        size_t r_size=0;
        char* imagebyte=nullptr;

        FILE *fp = nullptr;
        qDebug() << "open cJSON file" ;
        fp = fopen(path, "rb");
        if(nullptr == fp)
        {
            qDebug() << "Unable to open" << QString::fromLocal8Bit(path);
            goto bad;
        }
        fseek(fp, 0, SEEK_END);
        _size = static_cast<size_t>(ftell(fp));
        if(0!=fseek(fp, 0, SEEK_SET))
        {
            qDebug() << "Unable to SET" << QString::fromLocal8Bit(path);
            goto bad;
        }
        qDebug() << "_size:" << _size;
        r_size = _size - _size%1024+2048;
        //if(nullptr == imagebyte) imagebyte = (char*)malloc(r_size);
        if(nullptr == imagebyte) imagebyte = reinterpret_cast<char *>(malloc(r_size));
        if(nullptr == imagebyte)
        {
            qDebug() << "malloc space fail!";
            goto bad;
        }
        memset(imagebyte, 0x00, r_size);
        r_size = fread(imagebyte, 1, _size, fp);
        qDebug() << "r_size:" << r_size;
        if(_size != r_size)
        {
            qDebug() << "read music fail" ;
            goto bad;
        }
        fclose(fp);
        //qDebug("imagebyte: %s", imagebyte);
        return imagebyte;
    bad:
        if(nullptr != fp) fclose(fp);
        return nullptr;
    }
    int save(const char *path, const char* json_str)
    {
        size_t _size=0;
        size_t w_size=0;
        FILE* fp = nullptr;

        fp = fopen(path, "w+");
        if(nullptr == fp)
        {
            qDebug() << "Unable to open" << QString::fromLocal8Bit(path);
            goto bad;
        }
        if(0!=fseek(fp, 0, SEEK_SET))
        {
            qDebug() << "Unable to SET" << QString::fromLocal8Bit(path);
            goto bad;
        }
        _size = strlen(json_str);
        //qDebug() << "json size:" << _size;
        w_size = fwrite(json_str, 1, _size, fp);
        qDebug() << "w_size:" << w_size;
        if(_size != w_size)
        {
            qDebug() << "write cJSON fail" ;
            goto bad;
        }
        fclose(fp);
        return 0;

    bad:
        if(nullptr != fp) fclose(fp);
        return -1;
    }
};

#endif // CJSONFORMAT_H
